package dd.prog2.exercises.set12.a1;

public class Board {

	private int[] board = new int[42];
	private int player = 1;
	private int turnCounter = 0;
	private boolean gameOver = false;
	private int winner = 0;

	public Board() {
	}

	int get(int i){
		return board[i];
	}
	
	void reset(){
		for (int i = 0; i < board.length; i++) {
			board[i] = 0;
			player = 1;
			turnCounter = 0;
			gameOver = false;
			winner = 0;
		}
	}
	
	private void isGameOver() {
		// turnCounter=42? => draw
		if (turnCounter == 42) {
			winner = 0;
			gameOver = true;
		}
		// check winner horiz
		if (!gameOver) {
			for (int i = 0; i < 6; i++) {
				for (int j = 0; j < 4; j++) {
					if (board[i*7+j] != 0)
						if (board[i*7+j] == board[i*7+j + 1]
								&& board[i*7+j] == board[i*7+j + 2]
								&& board[i*7+j] == board[i*7+j + 3]) {
							winner = board[i*7+j];
							gameOver = true;
						}
				}
			}
		}
		// check winner vertical
		if (!gameOver) {
			for (int i = 0; i < 3; i++) {
				for (int j = 0; j < 7; j++) {
					if (board[i*7+j] != 0)
						if (board[i*7+j] == board[(i+1)*7+j]
								&& board[i*7+j] == board[(i+2)*7+j]
								&& board[i*7+j] == board[(i+3)*7+j]) {
							winner = board[i*7+j];
							gameOver = true;
						}
				}
			}
		}
		// check winner diag right
		if (!gameOver) {
			for (int i = 0; i < 3; i++) {
				for (int j = 0; j < 4; j++) {
					if (board[i*7+j] != 0)
						if (board[i*7+j] == board[(i+1)*7+j + 1]
								&& board[i*7+j] == board[(i+2)*7+j + 2]
								&& board[i*7+j] == board[(i+3)*7+j + 3]) {
							winner = board[i*7+j];
							gameOver = true;
						}
				}
			}
		}
		// check winner diag left
		if (!gameOver) {
			for (int i = 0; i < 3; i++) {
				for (int j = 3; j < 7; j++) {
					if (board[i*7+j] != 0) {
						if (board[i*7+j] == board[(i+1)*7+j - 1]
								&& board[i*7+j] == board[(i+2)*7+j - 2]
								&& board[i*7+j] == board[(i+3)*7+j - 3]) {
							winner = board[i*7+j];
							gameOver = true;
						}

					}
				}
			}
		}
	}

	// setter
	public void setTurn(int index) {
		board[index] = player;
		turnCounter++;
		if (player == 1)
			player = 2;
		else
			player = 1;
		if (turnCounter > 4)
			isGameOver();
		// return "Success";
	}

	// getter
	public int getPlayer() {
		return player;
	}

	public int getWinner() {
		return winner;
	}

	public boolean getGameOver() {
		return gameOver;
	}
}
